package cn.gailvlun.gll.widget;

import android.content.Context;
import android.databinding.BindingAdapter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.makeramen.roundedimageview.RoundedImageView;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.util.DensityUtil;
import cn.gailvlun.gll.util.LogUtil;



public class ImageGroupView extends LinearLayout implements View.OnClickListener {

    public int DEFAULT_IMAGE_SIZE;
    private int LINE_COUNT = 3;
    private int SPACE;
    private List<String> imageList;
    private LinkedList<ImageView> viewCache;
    private LinkedList<LinearLayout> containerCache;
    private OnPhotoClickListener mOnPhotoClickListener;

    public ImageGroupView(Context context) {
        this(context, null);
    }

    public ImageGroupView(Context context, AttributeSet attrs) {
        super(context, attrs);

        DEFAULT_IMAGE_SIZE = DensityUtil.dp2px(context, 90);
        SPACE = DensityUtil.dp2px(context, 3);

        viewCache = new LinkedList<>();
        containerCache = new LinkedList<>();
        imageList = new ArrayList<>(4);
        setOrientation(VERTICAL);
    }

    @BindingAdapter("imageList")
    public static void setImageList(ImageGroupView igv, List<String> imageList) {
        if (igv != null) {
            igv.setImageList(imageList);
        }
    }

    @BindingAdapter("imageClick")
    public static void setOnPhotoClickListener(ImageGroupView igv, ImageGroupView.OnPhotoClickListener onPhotoClickListener) {
        if (igv != null) {
            igv.setOnPhotoClickListener(onPhotoClickListener);
        }
    }

    public void setImageList(List<String> imageList) {
        if (null != imageList) {
            this.imageList.clear();
            this.imageList.addAll(imageList);
            changeLayout();
        }
    }

    public void setImageList(String imageList) {
        if (null != imageList) {
            this.imageList.clear();
            this.imageList.add(imageList);
            changeLayout();
        }
    }

    public void setOnPhotoClickListener(OnPhotoClickListener onPhotoClickListener) {
        this.mOnPhotoClickListener = onPhotoClickListener;
    }

    private void changeLayout() {
        resetView();
        LinearLayout ll = provideContainer();
        addView(ll);
        for (int i = 0; i < imageList.size(); ++i) {
            final ImageView image = provideImageView();
            image.setTag(Integer.MAX_VALUE, i);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                image.setTransitionName(getContext().getString(R.string.shared_image) + i);
            }

            ll.addView(image);
            LogUtil.d("imageSource: " + imageList.get(i));
            RequestOptions options;

            options = RequestOptions.placeholderOf(R.drawable.bg_emotion_load_image_placeholder_middle);
            options.override(DEFAULT_IMAGE_SIZE);



            Glide.with(this)
                    .load(imageList.get(i))
                    .apply(options)
                    .into(new ImageViewTarget<Drawable>(image) {
                        @Override
                        protected void setResource(@Nullable Drawable resource) {
                            if (resource != null) {
                                changeImage(image, resource);
                            }
                        }
                    });

            LayoutParams lp = (LayoutParams) image.getLayoutParams();
            lp.setMargins(0, 0, 0, 0);
            if (imageList.size() > 4) {
                LINE_COUNT = 3;
                if (i % LINE_COUNT == LINE_COUNT - 1) {
                    ll = provideContainer();
                    LayoutParams llp = (LayoutParams) ll.getLayoutParams();
                    llp.setMargins(0, SPACE, 0, 0);
                    addView(ll);
                } else {
                    lp.setMargins(0, 0, SPACE, 0);
                }
            } else if (imageList.size() == 4) {
                LINE_COUNT = 2;
                if (i % LINE_COUNT == LINE_COUNT - 1) {
                    ll = provideContainer();
                    LayoutParams llp = (LayoutParams) ll.getLayoutParams();
                    llp.setMargins(0, SPACE, 0, 0);
                    addView(ll);
                } else {
                    lp.setMargins(0, 0, SPACE, 0);
                }

            } else {
                int space = i > 0 ? SPACE : 0;
                lp.setMargins(space, 0, 0, 0);
            }
        }

        if (imageList.size() == 0) {
            setVisibility(GONE);
        } else {
            setVisibility(VISIBLE);
        }
    }

    private void changeImage(ImageView image, Drawable resource) {
        int width, height;
        int resourceHeight = resource.getIntrinsicHeight();
        int resourceWidth = resource.getIntrinsicWidth();
        LogUtil.d("w:" + resourceWidth + ":::h:" + resourceHeight);
        if (imageList.size() < 2) {

            





















            if (resourceHeight > resourceWidth) {
                width = DensityUtil.dp2px(getContext(), 180 * resourceWidth / resourceHeight);
                height = DensityUtil.dp2px(getContext(), 180);
            } else {
                width = DensityUtil.dp2px(getContext(), 180);
                height = DensityUtil.dp2px(getContext(), 180 * resourceHeight / resourceWidth);
            }
        } else {
            width = DEFAULT_IMAGE_SIZE;
            height = DEFAULT_IMAGE_SIZE;
        }
        ViewGroup.LayoutParams lp = image.getLayoutParams();
        lp.width = width;
        lp.height = height;
        image.setImageDrawable(resource);
    }

    private void resetView() {
        for (int i = getChildCount() - 1; i > -1; --i) {
            LinearLayout child = (LinearLayout) getChildAt(i);
            removeView(child);
            LayoutParams lp = (LayoutParams) child.getLayoutParams();
            lp.setMargins(0, 0, 0, 0);
            cacheImageView(child);
            containerCache.add(child);
        }
    }

    private void cacheImageView(ViewGroup viewGroup) {
        for (int i = viewGroup.getChildCount() - 1; i > -1; --i) {
            ImageView child = (ImageView) viewGroup.getChildAt(i);
            viewGroup.removeView(child);
            viewCache.add(child);
        }
    }

    
    private LinearLayout provideContainer() {
        if (containerCache.isEmpty()) {
            LinearLayout ll = new LinearLayout(getContext());
            LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            ll.setLayoutParams(lp);
            ll.setOrientation(HORIZONTAL);
            return ll;
        }
        return containerCache.removeFirst();
    }

    private ImageView provideImageView() {
        if (viewCache.isEmpty()) {
            RoundedImageView riv = new RoundedImageView(getContext());
            int size = DensityUtil.dp2px(getContext(), 80);
            LayoutParams lp = new LayoutParams(size, size);
            riv.setLayoutParams(lp);
            riv.setCornerRadius(DensityUtil.dp2px(getContext(), 4));
            riv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            riv.setOnClickListener(this);
            return riv;
        }
        return viewCache.removeFirst();
    }

    @Override
    public void onClick(View v) {
        int position = (int) v.getTag(Integer.MAX_VALUE);
        if (mOnPhotoClickListener != null) {
            mOnPhotoClickListener.onItemClick((ImageView) v, imageList, position);
        }
    }

    public interface OnPhotoClickListener {
        void onItemClick(ImageView iv, List<String> photos, int position);
    }

}
